import type { JSX } from "react";
import { Navigate, useLocation } from "react-router-dom";

interface ProtectedRouteProps {
  children: JSX.Element;
  role?: string;
}

const ProtectedRoute = ({ children, role }: ProtectedRouteProps) => {
  const location = useLocation();
  const token = localStorage.getItem('token');
  const userData = localStorage.getItem('user');
  const user = userData ? JSON.parse(userData) : null;
  // 检查是否登录
  if (!token || !user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  // 检查角色权限
  if (role && user.role !== role) {
    return <Navigate to="/403" replace />; // 无权限页面
  }
  return children;
};

export default ProtectedRoute;